/* 1、读取本地数据存储，没有则显示无信息提示，有则显示信息，取本地存储的未读数量，传递给首页框架
 * 2、从服务器拉取未读消息，同时存储本地
 * 3、链接及时消息服务器
 * 4、从服务器拉取回复库，启动回复插件
 * 5、当后台切换到前台时（当网络恢复时），触发检查及时服务器链接状态
 * */
mui.init({
	gestureConfig: {
		tap: true,
		doubletap: true,
		longtap: true
	}
});
//变量定义 开始
var alldata = [];
var msgreply = true;
var Msgurl = getApiUrl('http://www.jiaoyou0.cn', 'chatsnew/getMessagebox');
var Msgdata = plus.storage.getItem('MsgData');
var lfdata = plus.storage.getItem('LaiData');
var WebId_index = plus.webview.getWebviewById('ParentFrame');
var WebId_chat = plus.webview.getWebviewById('Msg_Chat');
var qiantai = 'qiantai';
//变量定义 结束
//页面配置和监听 开始
plus.webview.currentWebview().setStyle({
	scrollIndicator: 'none'
});

document.addEventListener('internet', function(event) {
	
	if(event.detail.internet) {
		gotowokerman('close');
		DingTimeReply.Initialization();
	} else {
		msgreply = false;
		DingTimeReply.over();
	}
});


document.addEventListener("pause", function(){
	qiantai = 'houtai';
}, false);

document.addEventListener("resume", function(){
	if(qiantai == 'qiantai') return;
	qiantai = 'qiantai';
	DingTimeReply.Initialization();
}, false);

window.addEventListener('Chat_back', function(event) {
	var edata = {
		send_uid: event.detail.send_uid,
		nick_name: event.detail.nick_name,
		reply_type: event.detail.reply_type,
		headimg: event.detail.headimg,
		send_time: event.detail.send_time,
		content: event.detail.content,
		yuedu: 0
	};
	editlist2(edata)
});

var MsgClass = {
	reply_type: function(content, type) {
		var conmsg;
		switch(type) {
			case 0:
				conmsg = content;
				break;
			case 1:
				conmsg = '[照片]';
				break;
			case 2:
				conmsg = '[语音]';
				break;
			case 3:
				conmsg = '[小视频]';
				break;
			case 4:
				conmsg = '[礼物]';
				break;
			case 5:
				conmsg = '[语音通话]';
				break;
			case 7:
				conmsg = '[打招呼]';
				break;
			case 10:
				conmsg = content;
				break;	
			default:
				break
		}
		return conmsg;
	},
	contweidu: function(items) {
		var list = 0;
		mui.each(Msg.items, function(ii, value) {
			if(value.yuedu > 0) {
				list += value.yuedu;
			}
		})
		plus.runtime.setBadgeNumber(list);
		mui.fire(WebId_index, 'newmessages', {
			weidu: list
		})
	},
	getmessagebox: function() {
		mui.getJSON(Msgurl, '', function(data) {
			if(data.code == 200) {
				mui.each(data.data, function(index, datas) {
					im_push_storage(datas);
					editlist(datas);
				})
			} else if(data.code == 201) {} else {
				mui.toast(data.message)
			}
		})
	}
}

//页面配置和监听 结束
var liitem;
//流程 开始
//VUE绑定
var Msg = new Vue({
	el: '.mui-content',
	data: {
		items: alldata,
		lfang: {
			user_id: 0,
			headimg: '',
			nick_name: '',
			send_time: 0
		},
		lfs: 0
	},
	methods: {
		doThis: function(index) {
			if(this.items[index].yuedu != 0) {
				this.items[index].yuedu = 0;
				plus.storage.setItem('MsgData', JSON.stringify(Msg.items));
				MsgClass.contweidu(Msg.items)
			}
			if(this.items[index].reply_type==10){
				mui.openWindow({
					url: './page/GoUrl.html',
					id: 'GoUrl',
					extras: {
						gourl: this.items[index].gourl,
						title: this.items[index].nick_name
					}
				})
			}else{
				opentalk(this.items[index].send_uid, this.items[index].nick_name, this.items[index].headimg);
			}
		},
		offMsg: function(e, index) {
			e.target.style.transform = 'translate(0px,0px)';
			e.target.parentNode.parentNode.children[1].style.transform = 'translate(0px,0px)';
			plus.storage.removeItem("IM" + this.items[index].send_uid);
			this.items.splice(index, 1)

		},
		callyidu: function() {
			mui.confirm('是否把全部消息标记为已读？', '提示', ['是', '否'], function(e) {
				if(e.index == 0) {
					mui.each(Msg.items, function(key, item) {
						item.yuedu = 0;
					})
					plus.storage.setItem('MsgData', JSON.stringify(Msg.items))
					MsgClass.contweidu(Msg.items)
				}
			},'div')
		},
		openVisitor: function() {
			mui.openWindow({
				url: '../html/page/Visitor.html',
			})
		}
	},
	filters: {
		gettime: function(times) {
			var dates = new Date().getTime();
			var time = parseInt((dates - times * 1000) / 1000);
			var s;
			if(time < 60 * 10) {
				return '刚刚';
			} else if((time < 60 * 60) && (time >= 60 * 10)) {
				s = Math.floor(time / 60);
				return s + "分钟前";
			} else if((time < 60 * 60 * 24) && (time >= 60 * 60)) {
				s = Math.floor(time / 60 / 60);
				return s + "小时前";
			} else if((time < 60 * 60 * 24 * 3) && (time >= 60 * 60 * 24)) {
				s = Math.floor(time / 60 / 60 / 24);
				return s + "天前";
			} else {
				var date = new Date(parseInt(times) * 1000);
				return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
			}
		},
		getcontent: function(content, type) {
			if(type == null) {
				return content;
			}
			return MsgClass.reply_type(content, type);
		}
	},
	watch: {
		items: function() {
			plus.storage.setItem('MsgData', JSON.stringify(this.items))
			MsgClass.contweidu(this.items)
		}
	},
	computed: {
		listTemp: function() {
			var list = this.list;
			for(var i = 0; i < list.length; i += 1) {
				index = parseInt(i / sectionCount);
				if(arrTemp.length <= index) {
					arrTemp.push([])
				};
				arrTemp[index].push(list[i])
			};
			return arrTemp
		}
	}
})
/*流程 开始*/
//1、读取并判断本地是否有聊天存储
if(Msgdata) {
	alldata = JSON.parse(Msgdata);
	if(alldata.length > 0) {
		Msg.items = alldata;
		MsgClass.contweidu(alldata)
	}
}
if(lfdata) {
	lfdata = JSON.parse(lfdata);
	if(lfdata.length > 0) {
		Msg.lfang.user_id = lfdata[0].user_id;
		Msg.lfang.headimg = lfdata[0].headimg;
		Msg.lfang.nick_name = lfdata[0].nick_name;
		Msg.lfang.send_time = lfdata[0].send_time;
		Msg.lfs = lfdata.length;
	}
}
//2、从服务器上拉取
MsgClass.getmessagebox();
//3、链接及时服务器
gotowokerman();
/*流程 结束*/
/*基本函数  开始*/

function im_push_storage(data) {
	var imdata = new Array();
	var imchat = plus.storage.getItem('IM' + data.send_uid);
	if(imchat) {
		imchat = JSON.parse(imchat)
		if(imchat.length > 0) {
			imdata = imchat
		};
	}
	imdata.push(data);
	plus.storage.setItem('IM' + data.send_uid, JSON.stringify(imdata))
};

function opentalk(sid, title, rheadimg) {
	if(!WebId_chat) {
		WebId_chat = plus.webview.getWebviewById('Msg_Chat')
	};
	mui.fire(WebId_chat, 'getmessage', {
		id: sid,
		title: title,
		rheadimg: rheadimg
	});
//	WebId_chat.show();
	//	//	mui.fire(chatPage, 'getmessage');
	mui.openWindow({
		url: 'html/Msg_Chat.html',
		id: 'Msg_Chat'
	})
};

//消息列表更新
function editlist(data) {
	var wdu = 0;
	mui.each(Msg.items, function(ii, vaule) {
		if(vaule.send_uid == data.send_uid) {
			if(vaule.yuedu > 0) {
				wdu += vaule.yuedu;
			}
			Msg.items.splice(ii, 1)
			return false;
		}
	});
	data.yuedu = wdu + 1;
	Msg.items.unshift(data)
};

function editlist2(data) {
	mui.each(Msg.items, function(ii, vaule) {
		if(vaule.send_uid == data.send_uid) {
			Msg.items.splice(ii, 1)
			return false;
		}
	});
	Msg.items.unshift(data)
};
/*基本函数结束 开始*/
var ws;
var wsi = 0;

function gotowokerman(type) {
	if(type == 'close') {
		if(wsi == 1) return;
		wsi = 1;
		ws.close();
		setTimeout(function() {
			gotowokerman();
			wsi = 0;
		}, 2000)
		return;
	}
	ws = new WebSocket("ws://jiaoyou0.cn:8282");
	ws.onopen = function() {};
	ws.onmessage = function(e) {
		var data = JSON.parse(e.data);
		var url = getApiUrl('http://www.jiaoyou0.cn', 'chats/banguser');
		switch(data.type) {
			case 'init':
				mui.post(url, {
					client_id: data.client_id,
					user_id: configs.user_id
				}, function(data) {}, 'json');
				break;
			case 'ping':
				ws.send('{"type":"ping"}');
				break;
			case 'text':
				dojishicall(data.data,true,false);
				break;
			default:
		}
	};
	ws.onclose = function() {}
};

function laifang(data) {
	Msg.lfs += 1;
	Msg.lfang.user_id = data.user_id;
	Msg.lfang.headimg = data.headimg;
	Msg.lfang.nick_name = data.nick_name;
	Msg.lfang.send_time = data.send_time;
	var lfata = new Array();
	var lf = plus.storage.getItem('LaiData');
	if(lf) lfata = JSON.parse(lf);
	mui.each(lfata, function(ii, vaule) {
		if(data.user_id == vaule.user_id) {
			lfata.splice(ii, 1)
		}
	});
	lfata.unshift({
		user_id: data.user_id,
		headimg: data.headimg,
		nick_name: data.nick_name,
		send_time: data.send_time
	})
	plus.storage.setItem('LaiData', JSON.stringify(lfata))
}

plus.push.addEventListener( "receive", function( msg ) {
}, false );

var chatsPage = null;
plus.push.addEventListener("click", function(msg) {
	var datas = JSON.parse(msg.payload)
	if(datas.reply_type>=0){
		dojishicall(datas,false,false)
	}else{
		if(!chatsPage) {
			chatsPage = plus.webview.getWebviewById('Msg_Chat')
		}
		mui.fire(chatsPage, 'getmessage', {
			id: datas.send_uid,
			title: datas.nick_name,
			rheadimg: datas.headimg
		});
		chatsPage.show();
		plus.push.clear();
	}
}, false);

function dojishicall(data, type, houtai) {
	im_push_storage(data);
	editlist(data);
	if(!type) return;
	var conmsg = MsgClass.reply_type(data.content, data.reply_type);
	
	var title = data.nick_name;
	var optionss = {
		title: title,
		cover: true
	};
	var payload = '{"send_uid":'+data.send_uid + ',"nick_name":"' + data.nick_name + '","headimg":"' + data.headimg+'"}';
	

	mui.fire(WebId_chat, 'Msg_NowTime', {
		sid: data.send_uid,
		headimg: data.headimg,
		reply_type: data.reply_type,
		content: data.content
	});

	if(data.reply_type == 5) {
		if(!isvipcoin(false)){
			if(houtai==true || qiantai != 'houtai'){
				mui.openWindow({
					url: 'page/yuyin-jie.html',
					id: 'yuyin-jie',
					extras: {
						uid: data.send_uid,
						name: data.nick_name,
						headimg: data.headimg
					},
					waiting: {
						autoShow: false,
					},
					createNew: false,
				})
			}
		}
	}else{
		plus.push.createMessage(conmsg, payload, optionss);
	}
	
}

var backButtonPress = 0;
mui.back = function(event) {
	backButtonPress += 1;
	if(backButtonPress > 1) {
		plus.runtime.quit()
	} else {
		plus.nativeUI.toast('再按一次退出应用')
	};
	setTimeout(function() {
		backButtonPress = 0
	}, 1000);
	return false
};